package com.pys.utils;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.commons.lang.StringUtils;

public class ResourceUtil {

	public static String getResourceBundleString(String moduleBundleName,
			String key, Object[] parameters) {
		return getResourceBundleString(moduleBundleName, key, parameters, null);
	}

	public static String getResourceBundleString(String moduleBundleName,
			String key, Object[] parameters, Locale locale) {
		String value = null;

		Locale localLocale = null;
		if (locale == null)
			localLocale = getLocale();
		else
			localLocale = locale;
		if (locale == null) {
			if (getLocale() != null)
				localLocale = getLocale();
		}
		ResourceBundle bundle = ResourceBundle.getBundle(moduleBundleName,
				localLocale);
		if (bundle == null)
			return key;
		try {
			value = bundle.getString(key);
		} catch (MissingResourceException e) {
			value = key;
		}
		if (value == null)
			return StringUtils.EMPTY;
		if (parameters != null)
			value = MessageFormat.format(value, parameters);
		return value;
	}

	public static String getResourceBundleString(ResourceBundle bundle,
			String key, Object[] parameters) {
		if (bundle == null)
			return key;
		String value = null;
		try {
			value = bundle.getString(key);
		} catch (MissingResourceException e) {
			value = key;
		}
		if (value == null)
			return StringUtils.EMPTY;
		if (parameters != null)
			value = MessageFormat.format(value, parameters);
		return value;
	}

	public static Locale getLocale() {
		return Locale.getDefault();
	}

}
